#include <mex.h>
#include <windows.h>

#import "C:\\Users\\DENIS\\Desktop\\SvetlanaProject\\EAreader\\EAreader\\bin\Debug\\EAreader.tlb"

using namespace EAreader;

void CopyLong2Double(double * dest, long * data, int size)
{
	for(int i = 0; i < size; i++)
	{
		dest[i] = (double) data[i]; 
	}
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	if (nrhs != 1)
	{
		plhs[0] = mxCreateString("[ProblemsStart, ProblemsDuration, Severity] = GetProblems(EAblankPath)");
	}
	HRESULT hr = CoInitialize(NULL);
	EApdfreaderPtr Reader(__uuidof(EA_reader));
	long Start[3];
	long Duration[3];
	long t;
	char* FileName = mxArrayToString(prhs[0]);//"C://Users//DENIS//Desktop//SvetlanaProject//EAreader//Debug//B3_20110930_9838_FL2.pdf";
	Reader->ParseEvents(25, (long)FileName);
	int TableNum = Reader->GetNumberOfTables();


	plhs[0] = mxCreateDoubleMatrix(TableNum, 1, mxREAL);
	double * TableSize = mxGetPr(plhs[0]);


	double *** EventsStart = new double**[TableNum];
	double *** EventsDuration = new double**[TableNum];
	double ** SeverityLevel = new double*[TableNum];
	for(int i = 1; i <= TableNum; i++)
	{
		int EventNum = Reader->GetNumberOfEventsInTable(i);
		TableSize[i-1] = EventNum;
		EventsStart[i-1] = new double*[EventNum];
		EventsDuration[i-1] = new double*[EventNum];
		SeverityLevel[i-1] = new double[EventNum];
		for(int j = 1; j <= EventNum; j++)
		{
			long res[3];

			EventsDuration[i-1][j-1] = new double[3];
			EventsStart[i-1][j-1] = new double[3];

			Reader->GetEventStart(3, i, j, res);
			CopyLong2Double(EventsStart[i-1][j-1], res, 3);

			Reader->GetEventDuration(3, i, j, res);
			CopyLong2Double(EventsDuration[i-1][j-1], res, 3);

			SeverityLevel[i-1][j-1] = Reader->GetEventSeverity(i, j);
		}
	}
	

	int EventNum = 0;
	for(int i=0; i < TableNum; i++)
	{
		EventNum += TableSize[i];
	}

	plhs[1] =  mxCreateDoubleMatrix(EventNum, 3, mxREAL);
	plhs[2] =  mxCreateDoubleMatrix(EventNum, 3, mxREAL);
	plhs[3] =  mxCreateDoubleMatrix(EventNum, 1, mxREAL);

	double * StartTime = mxGetPr(plhs[1]);
	double * DurationTime = mxGetPr(plhs[2]);
	double * Severity = mxGetPr(plhs[3]);

	int Iterator = 0;

	for(int i = 0; i < TableNum; i++)
	{
		for( int j = 0; j< TableSize[i]; j++)
		{
			StartTime[Iterator] = EventsStart[i][j][0];
			StartTime[Iterator + EventNum] = EventsStart[i][j][1];
			StartTime[Iterator + 2*EventNum] = EventsStart[i][j][2];
			DurationTime[Iterator] = EventsDuration[i][j][0];
			DurationTime[Iterator + EventNum] = EventsDuration[i][j][1];
			DurationTime[Iterator + 2*EventNum] = EventsDuration[i][j][2];

			Severity[Iterator] = SeverityLevel[i][j];
			Iterator++;
		}
	}
	CoUninitialize();
}